const t = require('hy5b/t')
const read = require('hy5b/backend/read')
const write = require('hy5b/backend/write')
var path = require("path")

function main(filepath) {
  read.readFile(filepath, function(err, str) {
    if (err) {
      console.error(err)
      return
    }
    var pos = 0;
    var matched;
    while ((matched = t.matchBetween(str, /#### /, /\n/, pos)) !== -1) {
      const writeFile = path.resolve(matched.middleMatch.replace('~', path.resolve('./dist')));

      var mathedCode = t.matchBetween(str, /```go[\n]/, /```/, matched.endPos + matched.endMatch.length)
      if (mathedCode !== -1) {
        var code = mathedCode.middleMatch

        var writefs = write(writeFile);
        writefs.write(code);
        console.log('complete write to ' + writeFile)
        pos = matched.endPos + matched.endMatch.length;
      } else {
        console.error(writeFile + ' no code');
        break
      }
    }
  })
}

var argvs = process.argv;

if ((argvs.length - 2) < 1) {
  console.log("Usage: " + path.basename(argvs[0]) + " " + path.basename(argvs[1]) + " {file path}");
} else {
  main(argvs[2]);
}